<template>
  <div>
    <!-- 搜索条件 -->
    <el-card v-show="showQueryForm" class="form-card">
      <QueryForm ref="queryFormRef" :form-data="queryFormData" :items="queryFormItems" :model="queryFormData" :show-control="true" label-width="82px">
        <QueryFormItem label="应用类型" prop="type">
          <el-select v-model="queryFormData.type" clearable placeholder="请选择应用类型">
            <el-option :value="0" label="Android"/>
            <el-option :value="1" label="iOS"/>
          </el-select>
        </QueryFormItem>

        <template #control>
          <el-button icon="Search" type="info" @click="handleSearch">{{ $t('form.search') }}</el-button>
          <el-button icon="Refresh" @click="handleResetQueryForm">{{ $t('form.reset') }}</el-button>
        </template>
      </QueryForm>
    </el-card>

    <!-- 列表数据 -->
    <el-card class="content-card">
      <!-- 工具栏 -->
      <table-toolbar v-model:columns="columns"
                     v-model:show-query-form="showQueryForm"
                     v-model:size="size"
                     v-model:stripe="stripe"
                     @refresh="handleSearch">

        <!-- 操作区域 -->
        <el-button v-permission="'app:info:create'" icon="circle-plus" plain type="primary" @click="handleAppInfoFormShow(1, 0)">创建应用</el-button>
        <el-button v-permission="['app:info:create','app:info:version:create']" icon="upload" plain type="success" @click="handleAppPublishFormShow">发布应用</el-button>
      </table-toolbar>

      <!-- 列表记录 -->
      <div class="table-wrapper">
        <!-- 列表数据 -->
        <el-table ref="tableRef"
                  v-loading="loading"
                  :data="tableData"
                  :size="size"
                  :stripe="stripe"
                  row-key="id"
                  show-overflow-tooltip
                  @select="handleSelectChange"
                  @select-all="handleSelectAll"
                  @sort-change="handleSortChange">
          <template #empty>
            <el-empty class="table-empty" description="暂无数据"/>
          </template>

          <table-column :columns="columns">

            <template #name="scope">
              <div class="name-slot">
                <el-avatar v-if="scope.row.icon_url" :size="32" :src="scope.row.icon_url" class="avatar" shape="square"/>
                <span>{{ scope.row.name }}</span>
              </div>
            </template>

            <template #enabled="scope">
              <DictTag v-model="scope.row.enabled" dict-type="sys_enabled"/>
            </template>

            <template #type="scope">
              <SvgIcon v-if="scope.row.type === 0" class="icon_wrap android" icon="android-fill" size="22"/>
              <SvgIcon v-else-if="scope.row.type === 1" class="icon_wrap apple" icon="apple-fill" size="22"/>
            </template>

            <template #operations="scope">
              <el-button v-permission="'app:info:info'" link type="info" @click="handleAppInfoFormShow(0, scope.row.id)">查看</el-button>
              <el-button v-permission="'app:info:update'" link type="primary" @click="handleAppInfoFormShow(2, scope.row.id)">编辑</el-button>
            </template>
          </table-column>
        </el-table>

        <!-- 分页操作 -->
        <el-pagination v-if="totalCount > 0"
                       :current-page="pageQuery.pageNum"
                       :page-size="pageQuery.pageSize"
                       :page-sizes="pageSizes"
                       :total="totalCount"
                       background
                       class="table-pagination"
                       layout="total, sizes, prev, pager, next"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </el-card>

    <!-- 弹窗操作 -->
    <AppInfoForm ref="appInfoFormRef" @refresh="handleSearch"/>
    <!-- 应用发布操作 -->
    <AppPublishForm ref="appPublishFormRef" @refresh="handleSearch"/>
  </div>
</template>

<script lang="tsx" setup>
import { computed, onBeforeMount, reactive, ref } from 'vue';
import { QueryForm, QueryFormItem } from '@/components/query-form';
import useLoading from '@/hooks/use-loading';
import TableColumn, { TableColumnData } from '@/components/table-column/index.vue';
import TableToolbar from '@/components/table-toolbar/index.vue';
import useTableSelection from '@/hooks/use-table-selection';
import { TableInstance } from 'element-plus';
import useTable from '@/hooks/use-table.ts';
import { QueryFormItemRule } from '@/components/query-form/constants.ts';
import { DictTag } from '@/components/dict-tag';
import { appList } from '@/api/api-app.ts';
import AppInfoForm from '@/views/app/info/app-info-form.vue';
import AppPublishForm from '@/views/app/info/app-publish-form.vue';
import { SvgIcon } from '@/components/icon';
import { hasPermission } from '@/utils/permission.ts';
import { computedOperateWidth } from '@/utils';
import router from '@/router';

defineOptions({name: 'app-info-list'});

// 查询
const queryFormData = reactive({
  name: undefined,
  type: undefined,
});
const queryFormRef = ref<InstanceType<typeof QueryForm>>();
const queryFormItems = ref<QueryFormItemRule[]>([
  {type: 'input', prop: 'name', label: '应用名称', placeholder: '请输入应用名称', clearable: true},
]);

// 列表数据
const tableRef = ref<TableInstance>();
const tableData = ref<any[]>([]);
const totalCount = ref(0);

// 操作区域宽度计算
const operateWidth = computed(() => {
  let count = 0
  if (hasPermission('app:info:info')) count += 1
  if (hasPermission('app:info:update')) count += 1
  return computedOperateWidth(count);
});

// 列设置
const columns = ref<TableColumnData[]>([
  {prop: 'id', label: '编号', width: 105, align: 'center', sortable: 'custom'},
  {prop: 'name', label: 'App 名称', minWidth: 180, align: 'right', headerAlign: 'center', sortable: 'custom'},
  {prop: 'bundle_id', label: 'Bundle ID', minWidth: 160, align: 'right', headerAlign: 'center', sortable: 'custom'},
  {prop: 'type', label: '类型', width: 110, align: 'center', sortable: 'custom'},
  {prop: 'enabled', label: '状态', width: 110, align: 'center'},
  {prop: 'create_time', label: '创建时间', width: 180, align: 'center', sortable: 'custom'},
  {prop: 'update_time', label: '更新时间', width: 180, align: 'center', sortable: 'custom'},
]);

onBeforeMount(() => {
  if (operateWidth.value > 0) {
    columns.value.push({prop: 'operations', label: '操作', fixed: 'right', width: operateWidth.value, align: 'center', headerAlign: 'center'},)
  }
  // 重置查询表单
  handleResetQueryForm();
});

const [loading, setLoading] = useLoading(false);
const {tableMethods, tableState} = useTable(() => fetchDataList(), queryFormRef, true, true);
const {size, stripe, showQueryForm, pageQuery, pageSizes} = tableState;
const {handleSizeChange, handleCurrentChange, handleSortChange, handleResetForm} = tableMethods;
const {handleSelectChange, handleSelectAll, multipleSelection, clearSelection} = useTableSelection(tableData, tableRef);

// 数据查询
const fetchDataList = async () => {
  setLoading(true);
  try {
    // 查询数据
    const {data} = await appList({
      page_num: pageQuery.pageNum,
      page_size: pageQuery.pageSize,
      order_mode: pageQuery.orderMode,
      order_column: pageQuery.orderColumn,
      ...queryFormData,
    });
    // 结果转换
    tableData.value = data.list;
    totalCount.value = data.pages.total_count;
  } catch (err) {
  } finally {
    setLoading(false);
  }
};

// 刷新数据
const handleSearch = () => {
  fetchDataList();
};

// 重置查询条件
const handleResetQueryForm = () => {
  clearSelection();
  handleResetForm();
};

/** 添加/修改操作 */
const appInfoFormRef = ref<any>()
const handleAppInfoFormShow = (mode: number, id?: number) => {
  if (mode == 0) {
    router.push({path: '/app/info/' + id});
  } else {
    appInfoFormRef.value?.open(mode, id)
  }
};

/** 应用发布弹窗操作 */
const appPublishFormRef = ref<any>()
const handleAppPublishFormShow = () => {
  appPublishFormRef.value?.open()
};

</script>

<style lang="scss" scoped>
.name-slot {
  display: flex;
  align-items: center;

  .avatar {
    margin-right: 8px;
    background: unset !important;
  }
}

.icon_wrap {
  text-align: center;
  vertical-align: middle;

  &.android {
    color: rgba(139, 191, 82, 1);
  }

  &.apple {
    color: rgba(167, 178, 184, 1);
  }
}
</style>
